package com.help10000.rms.common.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.AbsoluteLayout;
import android.widget.ProgressBar;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.help10000.rms.R;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

public class ProgressWebView extends BridgeWebView {
    private ProgressBar mProgressBar;
    private WebChromeClient mWebChromeClient;

    public ProgressWebView(@NonNull Context context, AttributeSet attrs) {
        super(context, attrs);
        mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 8, 0, 0);
        mProgressBar.setLayoutParams(lp);
        //Drawable drawable = context.getResources().getDrawable(R.drawable.progressbar_webview);
        // 修改后（正确）
        Drawable drawable  = ContextCompat.getDrawable(getContext(), R.drawable.progressbar_webview);
        mProgressBar.setProgressDrawable(drawable);
        addView(mProgressBar);
        mWebChromeClient = new MyWebChromeClient();
        setWebChromeClient(mWebChromeClient);
        //是否可以缩放
        getSettings().setSupportZoom(false);
        getSettings().setBuiltInZoomControls(false);

    }

    public void setProgress(int newProgress){
        mProgressBar.setProgress(newProgress);
    }

    public static class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            ProgressWebView progressWebView = (ProgressWebView) view;
            if (newProgress == 100) {
                progressWebView.mProgressBar.setVisibility(GONE);
            } else {
                if (progressWebView.getVisibility() == GONE)
                    progressWebView.setVisibility(VISIBLE);

                progressWebView.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams) mProgressBar.getLayoutParams();
        lp.x = l;
        lp.y = t;
        mProgressBar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }
}
